package cn.cool.domain.trade.service.lock.filter;

import cn.cool.domain.trade.adapter.repository.ITradeRepository;
import cn.cool.domain.trade.model.entity.GroupBuyActivityEntity;
import cn.cool.domain.trade.model.entity.TradeLockRuleCommandEntity;
import cn.cool.domain.trade.model.entity.TradeLockRuleFilterBackEntity;
import cn.cool.domain.trade.service.lock.factory.TradeLockRuleFilterFactory;
import cn.cool.types.design.framework.link.model2.handler.ILogicHandler;
import cn.cool.types.enums.ResponseCode;
import cn.cool.types.exception.AppException;
import cn.hutool.core.util.ObjUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class UserTakeLimitRuleFilter
        implements ILogicHandler<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> {
    @Resource
    private ITradeRepository repository;

    @Override
    public TradeLockRuleFilterBackEntity apply(TradeLockRuleCommandEntity requestParameter, TradeLockRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("交易规则过滤-用户参与次数限制：{} activityId: {}", requestParameter.getUserId(), requestParameter.getActivityId());
        GroupBuyActivityEntity groupBuyActivity = dynamicContext.getGroupBuyActivity();

        Integer count = repository.queryOrderCountByActivityId(requestParameter.getActivityId(), requestParameter.getUserId());
        if (ObjUtil.isNotNull(groupBuyActivity.getTakeLimitCount()) && count >= groupBuyActivity.getTakeLimitCount()) {
            log.info("拼团活动 {} 不可以参与超过 {} 次", groupBuyActivity.getActivityId(), groupBuyActivity.getTakeLimitCount());
            throw new AppException(ResponseCode.E0103);
        }
        return TradeLockRuleFilterBackEntity.builder().userTakeOrderCount(count).build();
    }
}

























